/*
    pg_return_composite_data.c
*/
#include "postgres.h"
#include "funcapi.h"
#include "fmgr.h"
#include <stdio.h>
#include <string.h>

PG_MODULE_MAGIC;

PG_FUNCTION_INFO_V1(pg_return_composite_data);

Datum pg_return_composite_data(PG_FUNCTION_ARGS)
{
    char *name;
    int age;
    int len;
    TupleDesc tuple_desc;
    AttInMetadata *tuple_meta;
    char **tuple_values;
    HeapTuple tuple;
    Datum result;

    get_call_result_type(fcinfo, NULL, &tuple_desc);
    tuple_meta = TupleDescGetAttInMetadata(tuple_desc);

    name = PG_GETARG_CSTRING(0);
    age = PG_GETARG_INT32(1);

    /* TABLE (name CSTRING, age INTEGER) */
    /* 最终的结果表有两个数据项，因此填写 2 */
    tuple_values = palloc(2 * sizeof(char*)); 

    /* 为第一个数据项分配内存，填充数据 */
    len = strlen(name);
    tuple_values[0] = palloc0(sizeof(char) * (len + 1));
    memcpy(tuple_values[0], name, len);

    /* 第二个数据项 */
    tuple_values[1] = palloc0(sizeof(char) * (16));
    sprintf(tuple_values[1], "%d", age);

    tuple = BuildTupleFromCStrings(tuple_meta, tuple_values);
    result = HeapTupleGetDatum(tuple);

    PG_RETURN_DATUM(result);
}